import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import '../../blocs/sales.dart';
import '../../blocs/cart.dart';

class SalesListScreen extends StatefulWidget {
  SalesListScreen({Key? key}) : super(key: key);
  _SalesListStateScreen createState() => _SalesListStateScreen();
}

class _SalesListStateScreen extends State<SalesListScreen> {
  late SalesBloc listSourceRepository;

  @override
  void initState() {
    super.initState();
    listSourceRepository = new SalesBloc();
    listSourceRepository.criteria = {
      "category_id": "",
    };
  }

  @override
  void dispose() {
    listSourceRepository.dispose();
    super.dispose();
  }

  GlobalKey cartKey = GlobalKey();
  GlobalKey rootKey = GlobalKey();
  _login(BuildContext context) {
    App.router.navigateTo(context, AppRoutes.loginSignin);
  }

  _cancel() {}

  @override
  Widget build(BuildContext context) {
    print('sss');

    return Material(
        color: Color(0xffFF3434),
        child: LoadingMoreCustomScrollView(slivers: <Widget>[
          SliverAppBar(
              leadingWidth: 33.w,
              backgroundColor: Colors.white,
              brightness: Brightness.light,
              leading: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.pop(context);
                },
                child: Container(
                  child: Icon(
                    Icons.chevron_left,
                    color: AppColor.blackMain,
                    size: 32,
                  ),
                ),
              ),
              title: Row(
                children: <Widget>[
                  Text(
                    '限时抢购',
                    style: TextStyle(color: AppColor.blackMain),
                  ),
                ],
              ),
              actions: [
                Container(
                  margin: EdgeInsets.only(right: 21.w),
                  child: Consumer<CartBloc>(
                    builder: (context, _cart, child) => Builder(
                      builder: (context) {
                        return GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            if (_cart.amount == 0)
                              AppPopupService.showAlertSimple('I', '购物车是空的', '请先选择商品加入购物车，然后再结账哦');
                            else
                              App.router.navigateTo(context, AppRoutes.orderCart);
                          },
                          child: Badge(
                            badgeColor: Colors.red,
                            toAnimate: true,
                            shape: BadgeShape.circle,
                            borderRadius: BorderRadius.circular(20),
                            position: BadgePosition.topEnd(top: -2, end: -5),
                            animationType: BadgeAnimationType.scale,
                            child: Image.asset(
                              'assets/order/cart_circle.png',
                              key: cartKey,
                            ),
                            badgeContent: Text(_cart.amount.toString(),
                                style: TextStyle(color: Colors.white)),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ]),
          SliverList(
              delegate: SliverChildListDelegate([
            Container(
                width: 375.w,
                height: 147.h,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/homepage/限时抢购.png'),
                    fit: BoxFit.cover,
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(43)),
                ),
                child: Container(
                    padding: EdgeInsets.only(left: 141.w, top: 19.h),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        AppTextWidget.salesBannerTitle('限时抢购！'),
                        SizedBox(height: 14.h),
                        Container(
                          width: 208.w,
                          child: AppTextWidget.salesBannerDesc('限时抢购区域折扣多多，先到先得！ 更多优惠惊喜每天更新！'),
                        )
                      ],
                    )))
            // CachedNetworkImage(
            //   imageUrl: iv_img,
            //   fit: BoxFit.cover,
            // ),
          ])),
          LoadingMoreSliverList(
            SliverListConfig<Map>(
              itemBuilder: _SalesListStateScreen.generateItem,
              sourceList: listSourceRepository,
//                    showGlowLeading: false,
//                    showGlowTrailing: false,
              padding: EdgeInsets.symmetric(vertical: 20.0),
            ),
          )
        ]));
  }

  static Widget generateItem(BuildContext context, Map item, int index) {
    late Offset temp;
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          App.router.navigateTo(context, AppRoutes.productDetail + '?prod_id=${item['sku_id']}');
        },
        child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            width: 343.w,
            height: 161.h,
            margin: EdgeInsets.only(left: 16.w, right: 12.w, bottom: 10.h),
            padding: EdgeInsets.only(left: 22.w, top: 18.h),
            child: Column(children: [
              Row(
                children: <Widget>[
                  Container(
                    width: 80.w,
                    height: 80.h,
                    margin: EdgeInsets.only(
                      right: 27.w,
                    ),
                    child: CachedNetworkImage(
                      imageUrl: item['image_url'],
                      fit: BoxFit.cover,
                    ),
                  ),
                  Container(
                    width: 202.w,
                    height: 124.h,
                    padding: EdgeInsets.only(
                      left: 12.w,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                            height: 77.h,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Container(
                                    child: Text(
                                      item['sku_name'],
                                      softWrap: true,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: AppColor.nameProduct,
                                        fontWeight: FontWeight.w500,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 4.7.h),
                                  Text(
                                    item['sku_desc'],
                                    softWrap: true,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      color: AppColor.descProduct,
                                      fontWeight: FontWeight.normal,
                                      fontSize: 10.sp,
                                    ),
                                  ),
                                  SizedBox(height: 5.h),
                                  item['outstock_info'] == 1
                                      ? Container(
                                          width: 80.w,
                                          padding: EdgeInsets.symmetric(horizontal: 5.w),
                                          height: 16.h,
                                          decoration: BoxDecoration(
                                            color: Color(0xffFDE3E3),
                                            borderRadius: BorderRadius.circular(2),
                                          ),
                                          child: Center(
                                              child: Text('库存不足',
                                                  style: TextStyle(
                                                    color: Color(0xffFF3434),
                                                    fontSize: 10.sp,
                                                  ))))
                                      : Container(),
                                ])),
                        Row(children: [
                          Container(
                            height: 47.h,
                            width: 110.w,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  SizedBox(height: 8.h),
                                  Container(
                                    height: 14.h,
                                    child: Text(
                                      '\$' + item['origin_price'] + '/' + item['unit_desc'],
                                      softWrap: true,
                                      maxLines: 1,
                                      style: TextStyle(
                                        color: AppColor.nameProduct,
                                        fontWeight: FontWeight.normal,
                                        fontSize: 12.sp,
                                        decoration: TextDecoration.lineThrough,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 5.h),
                                  Container(
                                    height: 20.h,
                                    child: Text(
                                      '\$' + item['sku_price'] + '/' + item['unit_desc'],
                                      softWrap: true,
                                      maxLines: 1,
                                      style: TextStyle(
                                        color: Colors.red,
                                        fontWeight: FontWeight.normal,
                                        fontSize: 14.sp,
                                      ),
                                    ),
                                  )
                                ]),
                          ),
                          Column(children: [
                            SizedBox(height: 19.h),
                            Container(
                              width: 80.w,
                              height: 28.h,
                              child: Consumer<CartBloc>(
                                builder: (context, _cart, child) => Builder(
                                  builder: (context) {
                                    return Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: <Widget>[
                                        GestureDetector(
                                          onTap: () {
                                            _cart.reduceItem(item['sku_id']);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.minus_circle_outline,
                                            LineIcons.minusCircle,
                                            color: AppColor.nameProduct,
                                            size: 22,
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.symmetric(horizontal: 14.w),
                                          alignment: Alignment.center,
                                          child: Text(
                                            _cart.itemAmount(item['sku_id']).toString(),
                                            style: TextStyle(
                                              color: AppColor.nameProduct,
                                              fontWeight: FontWeight.normal,
                                              fontSize: 20.sp,
                                            ),
                                          ),
                                        ),
                                        GestureDetector(
                                          onPanDown: (details) {
                                            temp = new Offset(details.globalPosition.dx,
                                                details.globalPosition.dy);
                                          },
                                          onTap: () {
                                            late Function callback;
                                            // setState(() {
                                            _cart.addItem(item);
                                            OverlayEntry entry = OverlayEntry(builder: (ctx) {
                                              return ParabolaAnimateWidget(
                                                AppSession.homeRoot,
                                                temp,
                                                AppSession.homeCart,
                                                Icon(
                                                  Icons.add_circle,
                                                  color: Colors.redAccent,
                                                ),
                                                callback,
                                                duration: 800,
                                              );
                                            });

                                            callback = (status) {
                                              if (status == AnimationStatus.completed) {
                                                entry.remove();
                                              }
                                            };

                                            Overlay.of(AppSession.homeRoot.currentContext!)!.insert(entry);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.plus_circle,
                                            LineIcons.plusCircle,
                                            color: AppColor.nameProduct,
                                            size: 22,
                                          ),
                                        ),
                                      ],
                                    );
                                  },
                                ),
                              ),
                            ),
                          ])
                        ])
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 18.h),
            ])));
  }
}
